package com.tanchengjin.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanchengjin.admin.exception.SystemException;
import com.tanchengjin.admin.model.dao.AdminMenuMapper;
import com.tanchengjin.admin.model.dao.AdminPermissionMapper;
import com.tanchengjin.admin.model.dao.AdminRolePermissionMapper;
import com.tanchengjin.admin.model.pojo.AdminMenu;
import com.tanchengjin.admin.model.pojo.AdminPermission;
import com.tanchengjin.admin.model.pojo.AdminRolePermission;
import com.tanchengjin.admin.model.pojo.AdminUserRole;
import com.tanchengjin.admin.service.AdminPermissionService;
import com.tanchengjin.admin.service.AdminUserRoleService;
import com.tanchengjin.admin.service.AdministratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminPermissionServiceImpl extends ServiceImpl<AdminPermissionMapper, AdminPermission> implements AdminPermissionService {
    @Autowired
    private AdminPermissionMapper adminPermissionMapper;
    @Autowired
    private AdminMenuMapper adminMenuMapper;
    @Autowired
    private AdminRolePermissionMapper adminRolePermissionMapper;

    @Autowired
    private AdminUserRoleService adminUserRoleService;

    @Autowired
    private AdministratorService administratorService;

    @Override
    public List<AdminPermission> getAllByMenuId(int id) {
        AdminMenu adminMenu = adminMenuMapper.selectByPrimaryKey(id);
        if (adminMenu == null) throw new SystemException("不存在的菜单");
        return null;
    }

    @Override
    public List<AdminPermission> getAll() {
        List<AdminPermission> permissionList = new ArrayList<>();
        permissionList = adminPermissionMapper.getAll();
        return permissionList;
    }

    @Override
    public List<AdminPermission> getMenuTree() {

        List<AdminPermission> adminPermissionList = new ArrayList<>();
        QueryWrapper<AdminUserRole> adminUserRoleQueryWrapper = new QueryWrapper<>();
        adminUserRoleQueryWrapper.eq("admin_user_id", administratorService.getUser().getId());
        List<AdminUserRole> roles = adminUserRoleService.list(adminUserRoleQueryWrapper);

        //获取所有的权限
        QueryWrapper<AdminRolePermission> adminRolePermissionQueryWrapper = new QueryWrapper<>();
        adminRolePermissionQueryWrapper.in("admin_role_id", roles.stream().map(AdminUserRole::getAdminRoleId).toArray());
        List<AdminRolePermission> adminRolePermissions = adminRolePermissionMapper.selectList(adminRolePermissionQueryWrapper);

        List<Integer> ids = adminRolePermissions.stream().map(AdminRolePermission::getAdminPermissionId).collect(Collectors.toList());
        if (ids.size() >= 1) {
            QueryWrapper<AdminPermission> adminPermissionQueryWrapper = new QueryWrapper<>();
            adminPermissionQueryWrapper.in("id", ids);
            adminPermissionQueryWrapper.eq("type", 1).or().eq("type", 2);

            List<AdminPermission> permissionList = this.list(adminPermissionQueryWrapper);
            List<AdminPermission> adminPermissions = permissionList.stream().filter(e -> (e.getParentId() == null || e.getParentId() == 0)).collect(Collectors.toList());
            adminPermissionList = handleMenuTree(adminPermissions, permissionList);
        }
//        List<AdminPermission> adminPermissions = adminPermissionMapper.selectAndParentIdIsNull();
        return adminPermissionList;
    }

    private List<AdminPermission> handleMenuTree(List<AdminPermission> adminPermissionList, List<AdminPermission> currentAdminPermissionList) {
        for (AdminPermission adminPermission : adminPermissionList) {
//            List<AdminPermission> adminPermissions = adminPermissionMapper.selectByParentId(adminPermission.getId());
            List<AdminPermission> adminPermissions = currentAdminPermissionList.stream().filter(e -> (e.getParentId() != null && e.getParentId().equals(adminPermission.getId()))).collect(Collectors.toList());
            adminPermission.setChildren(adminPermissions);
            if (adminPermissions.size() >= 1) {
                this.handleMenuTree(adminPermissions, currentAdminPermissionList);
            }
        }
        return adminPermissionList;
    }

    /**
     * 为角色分配相应的权限
     *
     * @param roleId         角色id
     * @param permissionList 权限列表
     * @return 影响的记录数
     */
    @Transactional
    public int addPermissionByRoleId(int roleId, List<Integer> permissionList) {
        QueryWrapper<AdminRolePermission> adminRolePermissionQueryWrapper = new QueryWrapper<>();
        adminRolePermissionQueryWrapper.eq("admin_role_id", roleId);
        int row = adminRolePermissionMapper.delete(adminRolePermissionQueryWrapper);

        int i = adminRolePermissionMapper.batchInsert(roleId, permissionList);
        return i;
    }

    @Override
    public List<AdminPermission> getPermissionsByRoleId(int id) {
        List<Integer> ids = Collections.singletonList(id);
        List<AdminPermission> list = getPermissionsByRoleIds(ids);
        return list;
    }

    @Override
    public List<AdminPermission> getPermissionsByRoleIds(List<Integer> ids) {
        QueryWrapper<AdminPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("*");

        List<String> collect = ids.stream().map(String::valueOf).collect(Collectors.toList());
        String idsStr = String.join(",", collect);
        queryWrapper.apply("id in (select admin_permission_id from admin_role_permission where admin_role_id in ({0}))", idsStr);
        List<AdminPermission> list = this.list(queryWrapper);
        return list;
    }
}
